package 算法


object BinarySearch {
  def main(args: Array[String]): Unit = {
    val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14)
    val i = binarySearch(list.toArray, 14)
    println(i)

  }


  def binarySearch(arry: Array[Int], needed: Int): Int = {
    var left = 0
    var right = arry.length - 1
    while (left < right) {
      val mid: Int = (right - left) / 2 + left
      needed match {
        case _ if needed > arry.apply(mid) => left = mid
        case _ if needed < arry.apply(mid) => right = mid
        case _ if needed == arry.apply(mid) => return mid + 1
      }
    }
    return -1
  }


}
